package cn.wx.fileclient.service;

import cn.wx.fileclient.config.Environment;
import cn.wx.fileclient.entity.Applicant;
import cn.wx.fileclient.utils.ImageUtil;
import cn.wx.fileclient.utils.ReadLineUtils;
import cn.wx.fileclient.utils.Word2PDFUtil;
import javafx.application.Application;
import javafx.scene.control.Alert;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tools.ant.util.FileUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.Callable;

import static cn.wx.fileclient.utils.ReadLineUtils.getApplicantInfoFromPDF;

/**
 * 文件识别线程
 * Created by IntelliJ IDEA.
 * cn.wx.fileclient.service
 * name：FileRecognition
 * user：pengpeng
 * date:2020/11/2
 * time:16:58
 */
public class FileRecognition implements Callable<List<String>> {
    private static String SEVERIP = "http://127.0.0.1:8080";
    private List<String> filesList;
    private List<String> fileFailList = new ArrayList<>();
    private String scanDirection;
    private String success_Dir;
    private String fail_Dir;

    private Integer fileSuccessCont;

    public FileRecognition() {

    }

    public FileRecognition(String success_Dir, String fail_Dir, List<String> filesList, String scanDirection) {
        this.fileSuccessCont = 0;
        this.filesList = filesList;
        this.scanDirection = scanDirection;
        this.success_Dir = success_Dir;
        this.fail_Dir = fail_Dir;

    }

    @Override
    public List<String> call() {
        if (!CollectionUtils.isEmpty(filesList)) {
            //文件进行上传，失败或成功都转移到相应的文件下
            filesList.forEach(file -> {
                if (fileUpload(file)) {
                    fileTransferToSuccess(file);
                } else {
                    String fileD = fileTransferToFail(file);
                    if (null!=fileD)
                        fileFailList.add(fileD);
                }

            });
        }
        return fileFailList;
    }

    private String fileTransferToFail(String file) {
        try {
            File tFile = new File(file);
            if (tFile.isDirectory())
                return null;
            File fail = new File(fail_Dir);
            System.out.println("失败文件夹："+fail.getPath());
            if (!fail.exists())
                fail.mkdirs();

            File newFile = new File(fail.getPath()+"//"+tFile.getName());
            tFile.renameTo(newFile);
            System.out.println("失败文件移动成功");
            return fail.getPath()+"/"+tFile.getName();
        } catch (Exception e) {
            System.out.println("失败文件移动失败");
            return null;
        }
    }

    private String fileTransferToSuccess(String file) {
        try {
            File tFile = new File(file);
            if (tFile.isDirectory())
                return null;
            File success = new File(success_Dir);
            System.out.println("失败文件夹："+success.getPath());
            if (!success.exists())
                success.mkdirs();

            File newFile = new File(success.getPath()+"//"+tFile.getName());
            tFile.renameTo(newFile);
            System.out.println("失败文件移动成功");
            return success.getPath()+"/"+tFile.getName();
        } catch (Exception e) {
            System.out.println("文件移动失败");
            return null;
        }

    }

    //文件解析上传
    private Boolean fileUpload(String fileurl) {
       /* double random = Math.random();

        if (random<0.5)
            return true;
        else
            return false;*/
        try {
            if (StringUtils.isEmpty(fileurl))
                return false;
            //文件识别，进行参数识别
            Map<String, String> fileContenInfo = filefileRecognition(fileurl);
            //https://www.cnblogs.com/zwqh/p/9635176.html
            String res = null;
            File file = new File(fileurl);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(SEVERIP);

            httpPost.setEntity(getMutipartEntry(fileContenInfo, file));
            CloseableHttpResponse response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
            } else {
                res = EntityUtils.toString(entity, "UTF-8");
                response.close();
                throw new IllegalArgumentException(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //todo 文件识别 出些识别内容为空，则进行异常处理
    private Map<String, String> filefileRecognition(String fileurl) {
        String format = fileurl.substring(fileurl.indexOf(".")+1);
        Applicant applicant = new Applicant();
        switch (format){
            case "pdf":
                applicant = getApplicantInfoFromPDF(fileurl);
                break;
            case "doc":
                String pdfPath = Word2PDFUtil.convertToPDF(new File(fileurl));
                File pdfFile = new File(pdfPath);
                applicant = getApplicantInfoFromPDF(pdfFile);
                break;
            case "docx":
                String pdf = Word2PDFUtil.convertToPDF(new File(fileurl));
                File pdffile = new File(pdf);
                applicant = getApplicantInfoFromPDF(pdffile);
                break;
            default:
                applicant = ImageUtil.getInfoFromImage(fileurl);
        }

//        Applicant applicantInfoFromPDF = getApplicantInfoFromPDF(fileurl);
        //todo 文件识别
        return parseEntity(applicant);
    }

    //进行用户实体进行解析
    private Map<String, String> parseEntity(Applicant applicant) {
        if (applicant == null)
            return null;
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.isEmpty(applicant.getEmail()))
            map.put("email", applicant.getEmail());
        if (!StringUtils.isEmpty(applicant.getName()))
            map.put("name", applicant.getName());
        if (!StringUtils.isEmpty(applicant.getPhone()))
            map.put("phone", applicant.getPhone());
        if (!MapUtils.isEmpty(map))
            map.put("username", Environment.username);
        return map;
    }

    //获取传输实体
    private static MultipartEntity getMutipartEntry(Map<String, String> param, File file) throws UnsupportedEncodingException {
        if (file == null) {
            throw new IllegalArgumentException("文件不能为空");
        }
        FileBody fileBody = new FileBody(file);
        FormBodyPart filePart = new FormBodyPart("file", fileBody);

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart(filePart);
        param.forEach((k, v) -> {
            FormBodyPart field = null;
            try {
                field = new FormBodyPart(k, new StringBody((String) param.get(v)));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            multipartEntity.addPart(field);

        });

        return multipartEntity;
    }
}
